package infrastructure;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.log4j.Logger;

import common.messages.KVMessage;
import common.messages.KVMessage.MessageType;

public class MarshallerKvMessage {
	private Logger logger = LoggingManager.CreateServerLogger(MarshallerKvMessage.class);
	
	private JAXBContext jaxbContext;
	private Marshaller jaxbMarshaller;
	private Unmarshaller jaxbUnmarshaller;
	
	
	public MarshallerKvMessage() throws JAXBException{
		this.jaxbContext = JAXBContext.newInstance(KVMessageImp.class);
		this.jaxbMarshaller = jaxbContext.createMarshaller();
		this.jaxbUnmarshaller = jaxbContext.createUnmarshaller();
		this.jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
	}
	
	
	public KVMessage getKVMessage(byte [] bytes){		
		ByteArrayInputStream streamBytesInput = new ByteArrayInputStream(bytes);	
		KVMessage message = new KVMessageImp(MessageType.UNKNOWN, "");
		try {
			message = (KVMessage) jaxbUnmarshaller.unmarshal(streamBytesInput);						
		} catch (JAXBException e) {			
			logger.error(e);
		} 
		
		try {
			streamBytesInput.close();
		} catch (IOException e) {
			logger.error(e);
		}			
		
		return message;		
	}
	
	public byte [] getBytes(KVMessage message){		
		ByteArrayOutputStream streamBytesOutput = new ByteArrayOutputStream();
		byte [] returnBytes = null;
		try {				 
			jaxbMarshaller.marshal(message, streamBytesOutput);
			returnBytes = streamBytesOutput.toByteArray();
		} catch (JAXBException e) {
			logger.error(e);
		} 
					
		try {
			streamBytesOutput.close();
		} catch (IOException e) {
		}			
		
		return returnBytes;
	}
}
